import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useThemeStore = defineStore('theme', () => {
  // 当前主题模式，默认为浅色模式
  const isDark = ref(false)
  
  // 切换主题模式
  function toggleTheme() {
    isDark.value = !isDark.value
    // 动态添加或移除html元素的dark类
    if (isDark.value) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
  
  // 设置主题模式
  function setTheme(dark) {
    isDark.value = dark
    if (dark) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
  
  // 初始化主题
  function initTheme() {
    if (isDark.value) {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
  
  return { isDark, toggleTheme, setTheme, initTheme }
}, 
{
  // 开启持久化
  persist: true,
}) 